import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber, Switch, Tabs, Row, Col, Statistic } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined, BarChartOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import ActivityForm from './ActivityForm';
import ActivityDetailModal from './ActivityDetailModal';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 根据优惠券类型获取颜色
const getTypeColor = (type) => {
  const colorMap = {
    0: 'blue',
    1: 'green',
    2: 'orange',
    3: 'purple',
  };
  return colorMap[type] || 'default';
};

// 获取优惠活动列表
const fetchActivities = async (params) => {
  return request('/api/v1/coupon/activity', {
    method: 'GET',
    params,
  });
};

// 获取优惠活动详情
const fetchActivityDetail = async (id) => {
  return request(`/api/v1/coupon/activity/${id}`, {
    method: 'GET',
  });
};

// 创建优惠活动
const createActivity = async (data) => {
  return request('/api/v1/coupon/activity', {
    method: 'POST',
    data,
  });
};

// 更新优惠活动
const updateActivity = async (data) => {
  return request(`/api/v1/coupon/activity/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除优惠活动
const deleteActivity = async (id) => {
  return request(`/api/v1/coupon/activity/${id}`, {
    method: 'DELETE',
  });
};

// 获取优惠券列表
const fetchCoupons = async (params) => {
  return request('/api/v1/coupon', {
    method: 'GET',
    params: { ...params, status: 1 }, // 只获取状态为正常的优惠券
  });
};

// 获取门店列表
const fetchStores = async (params) => {
  return request('/api/v1/store', {
    method: 'GET',
    params: { ...params, pageSize: 999 },
  });
};

// 获取场地列表
const fetchVenues = async (params) => {
  return request('/api/v1/venue', {
    method: 'GET',
    params: { ...params, pageSize: 999 },
  });
};

const CouponActivity = () => {
  const [activities, setActivities] = useState([]);
  const [coupons, setCoupons] = useState([]);
  const [stores, setStores] = useState([]);
  const [venues, setVenues] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [activityForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentActivity, setCurrentActivity] = useState(null);
  const [formTitle, setFormTitle] = useState('创建优惠活动');
  const [activeTab, setActiveTab] = useState('running');

  // 获取优惠活动列表
  const fetchActivityList = async () => {
    try {
      setLoading(true);
      const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
      
      // 根据不同的tab构建不同的过滤条件
      const tabFilters = {};
      if (activeTab === 'running') {
        // 进行中：当前时间在活动时间范围内且状态为启用(1)
        tabFilters.status = 1;
        tabFilters.start_time_lte = now; // 开始时间小于等于当前时间
        tabFilters.end_time_gte = now;   // 结束时间大于等于当前时间
      } else if (activeTab === 'notStarted') {
        // 未开始：开始时间大于当前时间且状态为启用(1)
        tabFilters.status = 1;
        tabFilters.start_time_gt = now;
      } else if (activeTab === 'ended') {
        // 已结束：结束时间小于当前时间且状态为启用(1)
        tabFilters.status = 1;
        tabFilters.end_time_lt = now;
      } else if (activeTab === 'disabled') {
        // 已禁用：状态为禁用(0)
        tabFilters.status = 0;
      }
      
      const res = await fetchActivities({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...tabFilters,
        ...searchParams,
      });
      if (res.success) {
        setActivities(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total || 0,
        });
      } else {
        message.error(res.message || '获取优惠活动列表失败');
      }
    } catch (error) {
      console.error('获取优惠活动列表出错:', error);
      message.error('获取优惠活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取优惠券、门店、场地列表
  const fetchInitialData = async () => {
    try {
      setLoading(true);
      const [couponRes, storeRes, venueRes] = await Promise.all([
        fetchCoupons({}),
        fetchStores({}),
        fetchVenues({}),
      ]);

      if (couponRes.success) {
        setCoupons(couponRes.data.list || []);
      } else {
        message.error(couponRes.message || '获取优惠券列表失败');
      }

      if (storeRes.success) {
        setStores(storeRes.data.list || []);
      } else {
        message.error(storeRes.message || '获取门店列表失败');
      }

      if (venueRes.success) {
        setVenues(venueRes.data.list || []);
      } else {
        message.error(venueRes.message || '获取场地列表失败');
      }
    } catch (error) {
      console.error('获取初始数据出错:', error);
      message.error('获取初始数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchActivityList();
  }, [pagination.current, pagination.pageSize, searchParams, activeTab]);

  useEffect(() => {
    fetchInitialData();
  }, []);

  // 查看活动详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchActivityDetail(record.id);
      if (res.success) {
        // 处理优惠券数据
        if (res.data.type === 3 && res.data.coupon_ids) {
          try {
            const couponIds = JSON.parse(res.data.coupon_ids);
            if (couponIds.length > 0) {
              // 获取优惠券详情
              const couponRes = await request('/api/v1/coupon/batch', {
                method: 'POST',
                data: { ids: couponIds }
              });
              if (couponRes.success) {
                res.data.coupons = couponRes.data || [];
              }
            }
          } catch (e) {
            console.error('处理优惠券数据错误:', e);
          }
        }
        setCurrentActivity(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取活动详情失败');
      }
    } catch (error) {
      console.error('获取活动详情出错:', error);
      message.error('获取活动详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加活动
  const handleAdd = () => {
    setFormTitle('创建优惠活动');
    setCurrentActivity(null); // 确保 initialValues 为 null
    setFormVisible(true);
  };

  // 处理编辑活动
  const handleEdit = async (record) => {
    try {
      setLoading(true);
      // 获取活动详情，确保有完整数据
      const res = await fetchActivityDetail(record.id);
      if (res.success) {
        setFormTitle('编辑优惠活动');
        setCurrentActivity(res.data);
        setFormVisible(true);
      } else {
        message.error(res.message || '获取活动详情失败');
      }
    } catch (error) {
      console.error('编辑活动出错:', error);
      message.error('编辑活动失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除活动
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteActivity(id);
      if (res.success) {
        message.success('删除优惠活动成功');
        fetchActivityList();
      } else {
        message.error(res.message || '删除优惠活动失败');
      }
    } catch (error) {
      console.error('删除优惠活动出错:', error);
      message.error('删除优惠活动失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await activityForm.validateFields();
      setLoading(true);

      // 转换金额为分
      if (values.min_amount) {
        values.min_amount = Math.round(values.min_amount);
      }
      if (values.discount_rate) {
        // 根据活动类型处理折扣率
        if (values.type === 0) { // 折扣类型
          values.discount_rate = Math.round(values.discount_rate); // 转为后端存储的折扣值
        } else { // 满减类型
          values.discount_rate = Math.round(values.discount_rate); // 转为分
        }
      } 
      console.log(values);
      // 转换字段名称以匹配后端API
      const apiData = {
        ...values,
        name: values.name,
        type: values.type,
        description: values.description,
        start_time: parseInt(values.start_time.format('X')),
        end_time: parseInt(values.end_time.format('X')),
        status: values.status ? 1 : 0,
        min_amount: values.min_amount || 0,
        discount_rate: values.discount_rate || 0,
        applicable_type: values.applicable_type,
        applicable_ids: values.applicable_ids?JSON.stringify(values.applicable_ids):"",
        available_weekdays: values.available_weekdays?JSON.stringify(values.available_weekdays):"",
        available_times: values.available_times?JSON.stringify(values.available_times.map(t => {
                    if (t ) {
                        return {
                            start: t[0].format('HH:mm'),
                            end: t[1].format('HH:mm'),
                        }
                    }
                    return null;
                }).filter(t => t !== null)):"",
      };

      // 处理优惠券IDs
      if (values.type === 3 && values.coupon_ids) {
        apiData.coupon_ids = values.coupon_ids;
      }

      let res;
      if (currentActivity) {
        // 更新
        apiData.id = currentActivity.id;
        res = await updateActivity(apiData);
      } else {
        // 创建
        res = await createActivity(apiData);
      }

      if (res.success) {
        message.success(`${currentActivity ? '更新' : '创建'}优惠活动成功`);
        setFormVisible(false);
        fetchActivityList();
      } else {
        message.error(res.message || `${currentActivity ? '更新' : '创建'}优惠活动失败`);
      }
    } catch (error) {
      console.error(`${currentActivity ? '更新' : '创建'}优惠活动出错:`, error);
      message.error(`${currentActivity ? '更新' : '创建'}优惠活动失败`);
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '活动类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => {
        const typeMap = {
          0: '折扣',
          1: '满减',
          2: '满赠',
          3: '送优惠券',
        };
        return <Tag color={getTypeColor(type)}>{typeMap[type] || '未知类型'}</Tag>;
      },
    },
    {
      title: '优惠内容',
      dataIndex: 'content',
      key: 'content',
      width: 150,
      render: (_, record) => {
        if (record.type === 0) {
          return `${record.discount_rate}折`;
        } else if (record.type === 1) {
          return `满${record.min_amount}减${record.discount_rate}元`;
        } else if (record.type === 3) {
          return `赠送指定优惠券`;
        } else {
          return record.content || '-';
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: 180,
      render: (text) => moment.unix(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      width: 180,
      render: (text) => moment.unix(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 1:
            color = 'green';
            text = '启用';
            break;
          case 0:
            color = 'red';
            text = '禁用';
            break;
          default:
            color = 'default';
            text = status;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => moment.unix(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此优惠活动吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              icon={<DeleteOutlined />}
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.type !== undefined) {
      params.type = values.type;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.start_time = values.dateRange[0].startOf('day').unix();
      params.end_time = values.dateRange[1].endOf('day').unix();
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建优惠活动
          </Button>
        </div>

        <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginBottom: 16 }}>
          <TabPane tab="进行中" key="running" />
          <TabPane tab="未开始" key="notStarted" />
          <TabPane tab="已结束" key="ended" />
          <TabPane tab="已禁用" key="disabled" />
        </Tabs>

        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="活动名称">
            <Input placeholder="请输入活动名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="活动类型">
            <Select placeholder="请选择活动类型" style={{ width: 150 }} allowClear>
              <Option value={0}>折扣</Option>
              <Option value={1}>满减</Option>
              <Option value={2}>满赠</Option>
              <Option value={3}>送优惠券</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="活动时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={activities}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />

        <ActivityDetailModal
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          activity={currentActivity}
          stores={stores}
          venues={venues}
        />

        <ActivityForm
          visible={formVisible}
          onCancel={() => setFormVisible(false)}
          onOk={handleFormSubmit}
          form={activityForm}
          formTitle={formTitle}
          coupons={coupons}
          loading={loading}
          initialValues={currentActivity}
        />

      </Card>
    </PageContainer>
  );
};

export default CouponActivity;